package com.janko.springbootbase.juc.threadPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author nyk
 * @Date 2021/4/23 15:52
 * @Version 1.0
 * @Desc
 */
public class MyThreadExecutor {

    /**
     * //当前线程池 核心数，最大线程数，保持活跃时间，执行单位，阻塞队列
     *  ThreadPoolExecutor(int corePoolSize,
     *                               int maximumPoolSize,
     *                               long keepAliveTime,
     *                               TimeUnit unit,
     *                               BlockingQueue<Runnable> workQueue)
     */


    public static void main(String[] args) {
        /** 创建一个 单线程的线程池 */
//        SingleThreadExecutor();
        /** */
        ScheduledThreadPoolExecutor();

    }

    /**
     * 01 创建一个可重用固定线程数的线程池
     * 创建一个单线程的线程池。这个线程池只有一个线程在工作，也就是相当于单线程串行执行所有任务。
     * 如果这个唯一的线程因为异常结束，那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。
     */
    private static void SingleThreadExecutor() {
        //创建一个可重用固定线程数的线程池
        ExecutorService executorServicePool= Executors.newSingleThreadExecutor();
        //创建实现了Runnable接口对象，Thread对象当然也实现了Runnable接口
        createThread(executorServicePool);
    }

    private static void FixedThreadExecutor() {
        //创建一个可重用固定线程数的线程池
        ExecutorService executorServicePool= Executors.newFixedThreadPool(2);
        //创建实现了Runnable接口对象，Thread对象当然也实现了Runnable接口
        createThread(executorServicePool);
    }

    private static void CachedThreadExecutor() {
        //创建一个可重用固定线程数的线程池
        ExecutorService executorServicePool= Executors.newCachedThreadPool();
        //创建实现了Runnable接口对象，Thread对象当然也实现了Runnable接口
        createThread(executorServicePool);
    }

    private static void ScheduledThreadPoolExecutor() {
        //创建一个可重用固定线程数的线程池
        ScheduledThreadPoolExecutor exec =new ScheduledThreadPoolExecutor(1);
        exec.scheduleAtFixedRate(new Runnable() {
            //每隔一段时间就触发异常
            @Override
            public void run() {
                //throw new RuntimeException();
                System.out.println("================");
            }

        }, 1000, 5000, TimeUnit.MILLISECONDS);

        exec.scheduleAtFixedRate(new Runnable() {
            //每隔一段时间打印系统时间，证明两者是互不影响的
            @Override
            public void run() {
                System.out.println(System.nanoTime());
            }
        }, 1000, 2000, TimeUnit.MILLISECONDS);
    }










    private static void createThread(ExecutorService executorServicePool) {
        Thread t1 =new MyThread();
        Thread t2 =new MyThread();
        Thread t3 =new MyThread();
        Thread t4 =new MyThread();
        //将线程放入池中进行执行
        executorServicePool.execute(t1);
        executorServicePool.execute(t2);
        executorServicePool.execute(t3);
        executorServicePool.execute(t4);
        //执行完毕之后 shutdown
        executorServicePool.shutdown();
    }
}
